﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WorkStation.Frameworks.Core.Threading.Tasks
{
    /// <summary>
    /// 任务队列池
    /// </summary>
    /// <typeparam name="TTask"></typeparam>
    public sealed class TaskExecutorQueuePool<TTask>
    {
        protected static ConcurrentDictionary<string, TaskExecutorQueue<TTask>> _Pool = new ConcurrentDictionary<string, TaskExecutorQueue<TTask>>();

        protected static TaskExecutorQueue<TTask> _Default;

        protected static object _Lock = new object();

        /// <summary>
        /// 获取任务队列
        /// </summary>
        /// <param name="queueName">队列名称</param>
        /// <returns></returns>
        public static TaskExecutorQueue<TTask> GetInstance(string queueName = null) 
        {
            if (queueName != null)
            {
                return _Pool.GetOrAdd(queueName, v =>
                {
                    return new TaskExecutorQueue<TTask>(v);
                });
            }
            else 
            {
                if (_Default == null)
                {
                    lock (_Lock)
                    {
                        if (_Default == null)
                        {
                            _Default = new TaskExecutorQueue<TTask>();
                        }

                        return _Default;
                    }
                }
                else 
                {
                    return _Default;
                }
            }
        }

        /// <summary>
        /// 释放
        /// </summary>
        public static void Dispose() 
        {
            foreach (var item in _Pool) 
            {
                item.Value.Dispose();
            }

            if (_Default != null) 
            {
                lock (_Lock) 
                {
                    if (_Default == null && _Default.TaskObject.Status == System.Threading.Tasks.TaskStatus.Running) 
                    {
                        _Default.Dispose();
                    }
                }
            }
        }
    }
}
